<template>
  <div class="page-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1 class="page-title">
        <i class="el-icon-bell" style="margin-right: 10px;"></i>
        通知公告管理
      </h1>
      <div class="header-decoration"></div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 查询区域卡片 -->
      <el-card class="search-card">
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="16">
            <el-form inline :model="searchForm" class="search-form">
              <el-form-item label="标题搜索">
                <el-input
                  v-model="searchForm.title"
                  placeholder="请输入公告标题关键词"
                  clearable
                  class="search-input">
                </el-input>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="searchForm.timeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="date-picker">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch" class="search-btn">
                  <i class="el-icon-search" style="margin-right: 5px;"></i>查询
                </el-button>
                <el-button @click="resetSearch" class="reset-btn">
                  <i class="el-icon-refresh" style="margin-right: 5px;"></i>重置
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8" class="text-right">
            <el-button type="primary" @click="openAddDialog" class="add-btn">
              <i class="el-icon-plus" style="margin-right: 5px;"></i>添加公告
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 表格区域卡片 -->
      <el-card class="table-card">
        <div class="table-header">
          <h2>公告列表</h2>
          <div class="table-stats">
            <span>总条数: {{ tableData.length }}</span>
          </div>
        </div>
        
        <el-table
          :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)"
          border
          style="width: 100%"
          height="550"
          class="custom-table"
          :row-class-name="tableRowClassName">
          <el-table-column 
            prop="id" 
            label="公告ID" 
            width="100" 
            align="center">
          </el-table-column>
          <el-table-column 
            prop="title" 
            label="公告标题" 
            width="200" 
            align="center">
            <template #default="scope">
              <div class="title-cell">{{ scope.row.title }}</div>
            </template>
          </el-table-column>
          <el-table-column 
            prop="content" 
            label="公告内容" 
            width="400" 
            align="center">
            <template #default="scope">
              <el-tooltip effect="dark" :content="scope.row.content" placement="top">
                <div class="content-cell">{{ scope.row.content.length > 20 ? scope.row.content.slice(0, 20) + '...' : scope.row.content }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column 
            prop="publisher" 
            label="发布人" 
            width="150" 
            align="center">
          </el-table-column>
          <el-table-column 
            prop="publishTime" 
            label="发布时间" 
            width="200" 
            align="center">
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button size="small" type="success" @click="openEditDialog(scope.row)" class="edit-btn">
                <i class="el-icon-edit" style="margin-right: 3px;"></i>编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)" class="delete-btn">
                <i class="el-icon-delete" style="margin-right: 3px;"></i>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-row type="flex" justify="center" style="margin-top: 10px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,10,20,50]"
            :page-size="pageSize"
            :total="tableData.length"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination">
          </el-pagination>
        </el-row>
      </el-card>
    </div>

    <!-- 添加对话框 -->
    <el-dialog 
      title="添加公告" 
      v-model="addDialogVisible" 
      width="50%"
      class="custom-dialog"
      :close-on-click-modal="false">
      <el-form 
        :model="addForm" 
        ref="addFormRef" 
        :rules="rules" 
        label-width="120px"
        class="form-container">
        <el-form-item label="公告ID" prop="id">
          <el-input v-model="addForm.id" placeholder="请输入公告ID" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入公告标题" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            v-model="addForm.content" 
            type="textarea" 
            rows="4" 
            placeholder="请输入公告内容"
            class="form-textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="addForm.publisher" placeholder="请输入发布人" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="addForm.publishTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发布时间"
            class="form-datepicker">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false" class="dialog-btn cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleAdd" class="dialog-btn confirm-btn">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog 
      title="编辑公告" 
      v-model="editDialogVisible" 
      width="50%"
      class="custom-dialog"
      :close-on-click-modal="false">
      <el-form 
        :model="editForm" 
        ref="editFormRef" 
        :rules="rules" 
        label-width="120px"
        class="form-container">
        <el-form-item label="公告ID" prop="id">
          <el-input v-model="editForm.id" disabled class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入公告标题" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            v-model="editForm.content" 
            type="textarea" 
            rows="4" 
            placeholder="请输入公告内容"
            class="form-textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="editForm.publisher" placeholder="请输入发布人" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="editForm.publishTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发布时间"
            class="form-datepicker">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="dialog-btn cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleUpdate" class="dialog-btn confirm-btn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 假设 axios 相关请求方法在 utils/axios.js 中，需根据实际路径调整
import { post, get } from '@/utils/axios.js'

// 表格数据与分页
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  title: '',
  timeRange: []
})

// 添加对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  id: '',
  title: '',
  content: '',
  publisher: '',
  publishTime: ''
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  title: '',
  content: '',
  publisher: '',
  publishTime: ''
})

// 表单验证规则
const rules = {
  id: [
    { required: true, message: '请输入公告ID', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  publisher: [
    { required: true, message: '请输入发布人', trigger: 'blur' }
  ],
  publishTime: [
    { required: true, message: '请选择发布时间', trigger: 'blur' }
  ]
}

// 分页方法
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页，保持分页逻辑一致性
}

function handleCurrentChange(val) {
  currentPage.value = val
}

// 表格行样式
function tableRowClassName({ row, rowIndex }) {
  // 隔行变色效果
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd';
}

// 获取所有公告数据
function getAllNotices() {
  get('/api/notice/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error('未查询到公告数据')
      tableData.value = []
    }
  })
}

// 处理搜索
function handleSearch() {
  // 标题搜索优先
  if (searchForm.title && searchForm.title.trim()) {
    get('/api/notice/searchByTitle', { title: searchForm.title }, (res) => {
      if (res.status === 1) {
        tableData.value = res.data
        ElMessage.success('查询成功')
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    })
  } 
  // 时间范围搜索
  else if (searchForm.timeRange && searchForm.timeRange.length === 2) {
    // 这里假设后端有按时间范围查询的接口，如果没有可以在前端过滤
    const filteredData = tableData.value.filter(item => {
      const publishTime = new Date(item.publishTime)
      const startTime = new Date(searchForm.timeRange[0])
      const endTime = new Date(searchForm.timeRange[1])
      return publishTime >= startTime && publishTime <= endTime
    })
    tableData.value = filteredData
    ElMessage.success('时间范围查询成功')
  } else {
    ElMessage.warning('请输入搜索条件')
  }
}

// 重置搜索
function resetSearch() {
  searchForm.title = ''
  searchForm.timeRange = []
  getAllNotices()
}

// 打开添加对话框
function openAddDialog() {
  // 重置表单数据
  addForm.id = ''
  addForm.title = ''
  addForm.content = ''
  addForm.publisher = ''
  addForm.publishTime = ''
  
  addDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (addFormRef.value) {
      addFormRef.value.clearValidate()
    }
  })
}

// 处理添加
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/notice/add', addForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('添加成功')
          addDialogVisible.value = false
          getAllNotices()
        } else {
          ElMessage.error(res.msg || '添加失败')
        }
      })
    }
  })
}

// 打开编辑对话框
function openEditDialog(row) {
  // 复制行数据到编辑表单
  editForm.id = row.id
  editForm.title = row.title
  editForm.content = row.content
  editForm.publisher = row.publisher
  editForm.publishTime = row.publishTime
  
  editDialogVisible.value = true
  
  // 下一次DOM更新后清除验证状态
  nextTick(() => {
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  })
}

// 处理更新
function handleUpdate() {
  editFormRef.value.validate((valid) => {
    if (valid) {
      post('/api/notice/updateById', editForm, (res) => {
        if (res.status === 1) {
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          getAllNotices()
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      })
    }
  })
}

// 处理删除
function handleDelete(id) {
  ElMessageBox.confirm(
    `确定要删除ID为【${id}】的公告吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    get('/api/notice/deleteById', { id }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功')
        getAllNotices()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除，不做额外操作
  })
}

// 页面加载时获取所有数据
onMounted(() => {
  getAllNotices()
})
</script>

<style scoped>
/* 基础样式 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4eaf1 100%);
  padding: 20px;
  box-sizing: border-box;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 30px;
  position: relative;
}

.page-title {
  color: #333;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  padding-bottom: 10px;
  position: relative;
  display: inline-flex;
  align-items: center;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  border-radius: 3px;
}

.header-decoration {
  height: 8px;
  background: linear-gradient(90deg, #409eff, #67c23a, #409eff);
  background-size: 200% 100%;
  border-radius: 4px;
  margin-top: 10px;
  animation: gradientMove 8s ease infinite;
}

/* 主内容区域 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

/* 卡片样式 */
.el-card {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  border: none;
  overflow: hidden;
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 搜索卡片 */
.search-card {
  background: #fff;
  padding: 20px;
}

.search-form {
  margin-bottom: 0;
}

.search-input {
  width: 280px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.search-input:focus {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.date-picker {
  width: 380px;
  border-radius: 6px;
}

.search-btn, .reset-btn, .add-btn {
  border-radius: 6px;
  padding: 8px 18px;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.search-btn {
  background: linear-gradient(90deg, #409eff, #66b1ff);
  border: none;
}

.search-btn:hover {
  background: linear-gradient(90deg, #3688e6, #52a3ff);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  background: linear-gradient(90deg, #f5f7fa, #e4e9ed);
  color: #606266;
  border: none;
}

.reset-btn:hover {
  background: linear-gradient(90deg, #e9ecef, #dcdfe6);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.add-btn {
  background: linear-gradient(90deg, #67c23a, #85ce61);
  border: none;
  animation: pulse 2s infinite;
}

.add-btn:hover {
  background: linear-gradient(90deg, #52b12c, #76c84e);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

/* 表格卡片 */
.table-card {
  background: #fff;
  padding: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(90deg, #f8f9fa, #f1f3f5);
  border-bottom: 1px solid #e9ecef;
}

.table-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.table-stats {
  color: #606266;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.6);
  padding: 5px 12px;
  border-radius: 15px;
}

/* 表格样式 */
.custom-table {
  border-radius: 0 0 12px 12px;
  overflow: hidden;
}

.custom-table th {
  background: linear-gradient(90deg, #f8f9fa, #f1f3f5);
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #e9ecef;
}

.table-row-even {
  background-color: #f9f9f9;
}

.table-row-odd {
  background-color: #ffffff;
}

.custom-table tr:hover > td {
  background-color: #f0f7ff !important;
  transition: background-color 0.3s ease;
}

.title-cell {
  font-weight: 500;
  color: #409eff;
  transition: all 0.3s ease;
}

.title-cell:hover {
  color: #1890ff;
  transform: translateX(3px);
}

.content-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: all 0.3s ease;
}

.content-cell:hover {
  color: #67c23a;
}

/* 按钮样式 */
.edit-btn, .delete-btn {
  border-radius: 4px;
  transition: all 0.2s ease;
  margin-right: 5px;
}

.edit-btn {
  background: linear-gradient(90deg, #67c23a, #85ce61);
  border: none;
}

.edit-btn:hover {
  background: linear-gradient(90deg, #52b12c, #76c84e);
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.delete-btn {
  background: linear-gradient(90deg, #f56c6c, #f78989);
  border: none;
}

.delete-btn:hover {
  background: linear-gradient(90deg, #e34e4e, #f57a7a);
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
}

.el-pagination__item {
  border-radius: 4px;
  margin: 0 3px;
  transition: all 0.2s ease;
}

.el-pagination__item:hover {
  transform: translateY(-2px);
}

.el-pagination__item.active {
  background: #409eff;
  border-color: #409eff;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.custom-dialog .el-dialog__header {
  background: linear-gradient(90deg, #409eff, #66b1ff);
  padding: 15px 20px;
}

.custom-dialog .el-dialog__title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.custom-dialog .el-dialog__close {
  color: #fff;
}

.custom-dialog .el-dialog__close:hover {
  color: #f0f0f0;
}

.form-container {
  padding: 10px 0;
}

.form-input, .form-textarea, .form-datepicker {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.form-input:focus, .form-textarea:focus, .form-datepicker:focus {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-textarea {
  resize: vertical;
}

.dialog-btn {
  border-radius: 6px;
  padding: 8px 20px;
  transition: all 0.3s ease;
  margin-left: 10px;
}

.confirm-btn {
  background: linear-gradient(90deg, #409eff, #66b1ff);
  border: none;
}

.confirm-btn:hover {
  background: linear-gradient(90deg, #3688e6, #52a3ff);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.cancel-btn {
  background: linear-gradient(90deg, #f5f7fa, #e4e9ed);
  color: #606266;
  border: none;
}

.cancel-btn:hover {
  background: linear-gradient(90deg, #e9ecef, #dcdfe6);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 动画效果 */
@keyframes gradientMove {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .search-input {
    width: 220px;
  }
  
  .date-picker {
    width: 320px;
  }
}

@media screen and (max-width: 992px) {
  .el-col {
    width: 100% !important;
  }
  
  .text-right {
    justify-content: flex-start;
    margin-top: 15px;
  }
  
  .search-input, .date-picker {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
